//
//  ConfirmOrderVC.swift
//  RPay
//
//  Created by CharlieLiao on 2017/7/8.
//  Copyright © 2017年 Charlie. All rights reserved.
//

import UIKit

class ConfirmOrderVC: BaseVC, UITableViewDataSource, UITableViewDelegate, CTAPIManagerCallBackDelegate, CTAPIManagerParamSource
{
    // MARK: - Init
    convenience init() {
        self.init(nibName: "ConfirmOrderView", bundle: nil)
    }
    
    // MARK: - Life Cycle
    
    override func loadView() {
        super.loadView()
        tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 10))
        tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 10))
        tableView.register(UINib(nibName: "MyOrderCell", bundle: nil), forCellReuseIdentifier: "CellID")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = LocalStr("确认订单")
        // Do any additional setup after loading the view.
        计算总价()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        // 把自己给弹掉
        if navigationController != nil &&
            navigationController!.topViewController != self
        {
            var viewControllers = navigationController!.viewControllers
            if let index = viewControllers.index(of: self) {
                viewControllers.remove(at: index)
                navigationController!.viewControllers = viewControllers
            }
        }
    }
    
    // MARK: - Table View Data Source
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath) as! MyOrderCell
        let goods = list[indexPath.row]
        cell.nameLabel.text = goods.name
        cell.orderIDLabel.text = LocalStr("商品编号:").appending(goods.id)
        cell.priceLabel.text = goods.priceStr
        cell.totalLabel.text = String(format: "%.2f", goods.price*Double(goods.num))
        cell.countLabel.text = "x".appending(goods.num.description)
        return cell
    }
    
    // MARK: - CTAPIManagerParamSource
    func params(forApi manager: CTAPIBaseManager!) -> [AnyHashable : Any]!
    {
        // 确认支付接口参数
        if manager == _confirmApiManager {
            return [kApiParamOrderId: orderId!]
        }
        
        // 提交订单接口参数
        var id = ""
        var name = ""
        var num = ""
        var price = ""
        
        for goods in list {
            id.append(goods.id)
            name.append(goods.name)
            num.append(goods.num.description)
            price.append(goods.priceStr)
            
            if list.last != goods {
                id.append(",")
                name.append(",")
                num.append(",")
                price.append(",")
            }
        }
        return [kApiParamGoodsId:id, kApiParamGoodsName:name, kApiParamGoodsNum:num, kApiParamGoodsPrice:price]
    }
    
    // MARK: - CTAPIManagerCallBackDelegate
    
    func managerCallAPIDidSuccess(_ manager: CTAPIBaseManager!)
    {
        hideLoading()
        // 提交订单
        if _buyApiManager == manager {
            // 提交订单成功后清空购物车
            for goods in list {
                UserShare.shared.removeFromCart(goods)
            }
            UserShare.shared.loginUser!.rhAccount -= Double(合计Label.text!)!
            UserShare.shared.saveShoppingCart()
            
            orderId = manager.fetchData(with: OrderIdReformer()) as? String
            
            // 弹出确认支付
            confirmPay()
            
            //
            _buyApiManager = nil
        }
            // 确认支付
        else if manager == _confirmApiManager {
            // 支付成功
            let vc = PaySucceedVC()
            vc.isBuy = true
            vc.price = 合计Label.text
            navigationController!.pushViewController(vc, animated: true)
        }
    }
    
    func managerCallAPIDidFailed(_ manager: CTAPIBaseManager!)
    {
        hideLoading()
        navigationController!.alert(manager.errorMessage)
        if manager == _buyApiManager {
            _buyApiManager = nil
            
        } else if manager == _confirmApiManager {
            let vc = MyOrderVC()
            navigationController!.pushViewController(vc, animated: true)
            _confirmApiManager = nil
        }
    }
    
    // MARK: - Event respond
    /// 点击提交按钮
    @IBAction func tapSubmitBtn()
    {
        self.showLoading()
        self.buyApiManager.loadData()
    }
    
    // MARK: - 私有方法
    ///
    private func 计算总价() {
        var 合计: Double = 0
        for goods in list! {
            合计 = 合计+goods.price*Double(goods.num)
        }
        合计Label.text = String(format: "%.2f", 合计)
    }
    
    /// 确认支付
    private func confirmPay() {
        let vc = ConfirmPayVC()
        vc.money = 合计Label.text!
        vc.didConfirmBtn = { [weak self] (vc) in
            self?.showLoading()
            self?.confirmApiManager.loadData()
        }
        vc.didCancelBtn = { [weak self] (vc) in
            let vc = MyOrderVC()
            self?.navigationController!.pushViewController(vc, animated: true)
        }
        present(vc, animated: true, completion: nil)
    }
    
    // MARK: - Get
    var list: [GoodsModel]!
    var orderId: String?
    
    @IBOutlet var tableView: UITableView!
    @IBOutlet var 合计Label: UILabel!
    
    private var _buyApiManager : BuyGoodsApiManager?
    var buyApiManager: BuyGoodsApiManager {
        if _buyApiManager == nil {
            _buyApiManager = BuyGoodsApiManager()
            _buyApiManager!.delegate = self
            _buyApiManager!.paramSource = self
        }
        return _buyApiManager!
    }
    
    private var _confirmApiManager: ConfirmPayApiManager?
    var confirmApiManager: ConfirmPayApiManager {
        if _confirmApiManager == nil {
            _confirmApiManager = ConfirmPayApiManager()
            _confirmApiManager!.delegate = self
            _confirmApiManager!.paramSource = self
        }
        return _confirmApiManager!
    }
}
